package com.easylinkin.linkappapi.wxminiapp;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class WeChatUtil {

	public static String encryptSessionKey(String sessionKey) {
		return Base64.getEncoder().encodeToString(sessionKey.getBytes(StandardCharsets.UTF_8));
	}
	
	public static String decryptSessionKey(String sessionKey) {
		return new String(Base64.getDecoder().decode(sessionKey.getBytes(StandardCharsets.UTF_8)));
	}
	
	/**
	 * 对微信返回的信息做解密
	 * <a href="https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html">
	 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html</a>
	 * @param ciphertext
	 * @param textKey
	 * @param iv
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String ciphertext, String textKey, String iv) throws Exception {

		byte[] cipherBytes = Base64.getDecoder().decode(ciphertext);
		byte[] keyBytes = Base64.getDecoder().decode(textKey);
		byte[] ivBytes = Base64.getDecoder().decode(iv);
		if (keyBytes.length != 16) {
			throw new RuntimeException("key must be 16 bit !");
		}

		SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(ivBytes));

		byte[] original = cipher.doFinal(cipherBytes);
		String originalString = new String(original, "utf-8");
		return originalString;

	}
}
